#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import abort
from flask import current_app
from flask import redirect, jsonify
from flask import render_template, g
from flask import request

from info import constants, db
from info.models import Category, News, User
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu
from info.utils.common import user_login_data


@profile_blu.route("/other_news_list")
@user_login_data
def other_news_list():
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数缺少")

    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == other.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route("/other_info")
@user_login_data
def other_info():
    """查看其他用户信息"""
    user = g.user
    # 获取其他用户id
    other_id = request.args.get("user_id")
    if not other_id:
        abort(404)
    # 查询用户模型
    other = None
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if user:
        if other.followers.filter(User.id == user.id).count() > 0:
            # if other in user.followed:
            is_followed = True

    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template("news/other.html", data=data)


@profile_blu.route("/user_follow")
@user_login_data
def user_follow():
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        follows = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_li = []
    for follow_user in follows:
        user_li.append(follow_user.to_dict())

    data = {
        "users": user_li,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("news/user_follow.html", data=data)


@profile_blu.route("/news_list")
@user_login_data
def user_news_list():
    user = g.user
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    collections = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.news_list.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_li": news_dict_li
    }
    return render_template("news/user_news_list.html", data=data)


@profile_blu.route("/news_release", methods=["get", "post"])
@user_login_data
def news_release():
    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 定义列表保存分类数据
        categories_dicts = []
        for category in categories:
            cate_dict = category.to_dict()
            categories_dicts.append(cate_dict)
        # 移除‘最新’分类
        categories_dicts.pop(0)
        data = {
            "categories": categories_dicts
        }
        return render_template("news/user_news_release.html", data=data)
    else:
        title = request.form.get("title")
        source = "个人发布"
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")
        if not all([title, source, digest, content, index_image, category_id]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")
        news = News()
        news.title = title
        news.digest = digest
        news.source = source
        news.content = content
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        news.category_id = category_id
        news.user_id = g.user.id
        # 1代表待审核状态
        news.status = 1
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
        return jsonify(errno=RET.OK, errmsg="新闻发布成功，等待审核")


@profile_blu.route("/collection")
@user_login_data
def user_collection():
    user = g.user
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    collections = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "collections": collection_dict_li
    }
    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/pass_info", methods=["get", "post"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == "GET":
        data = {"user_info": user.to_dict() if user else None}
        return render_template("news/user_pass_info.html", data=data)
    else:
        # 1获取参数
        req = request.json
        old_password = req.get("old_password")
        new_password = req.get("new_password")
        # 2 校验参数
        if not all([old_password, new_password]):
            return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
        # 更新数据
        user.password = new_password
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

        return jsonify(errno=RET.OK, errmsg="密码修改成功")


@profile_blu.route("/pic_info", methods=["get", "post"])
@user_login_data
def pic_info():
    user = g.user

    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_pic_info.html", data=data)
    else:
        # 如果是POST请求表示修改头像， 读取上传的图片
        try:
            avatar = request.files.get("avatar").read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="读取失败")
        # 上传头像
        try:
            # 使用自己封装的storage方法将图片上传到七牛云
            key = storage(avatar)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")
        # 保存头像地址
        user.avatar_url = key
        data = {
            "avatar_url": constants.QINIU_DOMIN_PREFIX + key
        }
        return jsonify(errno=RET.OK, errmsg="OK", data=data)

        # data = {
        #     "user_info": user.to_dict()
        # }
        # return render_template("news/user_pic_info.html", data=data)


@profile_blu.route("/base_info", methods=["get", "post"])
@user_login_data
def base_info():
    """基础资料
    最先判断是GET 还是 POST请求！！
    1 获取参数，昵称，个性签名，性别
    2 校验参数
    判断参数
    初始化对象并且加入数据库中
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if request.method == "GET":
        user_info = user.to_dict()
        data = {
            "user_info": user_info
        }
        return render_template("news/user_base_info.html", data=data)

    else:
        req = request.json
        nick_name = req.get("nick_name")
        signature = req.get("signature")
        gender = req.get("gender")
        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
        if gender not in ["MAN", "WOMAN"]:
            return jsonify(errno=RET.PARAMERR, errmsg="参数类型错误")

        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender

        return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route("/info")
@user_login_data
def get_user_info():
    """
    用户基本信息
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    user_info = user.to_dict()
    data = {
        "user_info": user_info
    }
    return render_template("news/user.html", data=data)
